package models

import (
	"crypto/md5"
	"fmt"
	"gitchina/kly_service/data"
	"gitchina/kly_service/util"
)

type OilCard struct {
	repo *data.PayRepo
}

func (o OilCard) Charge(memberId, waybillId int, amount float32, cardNo, remark string) (err error) {
	var flowId int64
	var pBalanceDto data.PlatformBalanceDto
	if o.repo == nil {
		o.repo = &data.PayRepo{}
		o.repo.BeginTx()
		defer func() {
			if err != nil {
				util.GetLogger().Error("[oilcard.Charge] - error%s", err.Error())
			}
			o.repo.EndTx(err == nil)
		}()
	}

	if flowId, err = o.repo.NewTransFlow(data.TransFlowDto{
		MemberId: memberId,
		TransNo:  fmt.Sprintf("%x", md5.Sum([]byte(string(waybillId)))),
		Amount:   amount,
		TypeId:   7,
		State:    0,
		Remark:   "油卡充值(运费)",
	}); err == nil {
		if pBalanceDto, err = o.repo.GetPlatformBalanceById(8); err == nil {
			pOldBalance := pBalanceDto.Balance
			pBalanceDto.Balance = pBalanceDto.Balance + amount
			if err = o.repo.UpdatePlatformBalance(&pBalanceDto, pOldBalance); err == nil {
				err = o.repo.NewOilCardRecord(data.OilCardDto{
					MemberId: memberId,
					FlowId:   flowId,
					Amount:   amount,
					CardNo:   cardNo,
					CardType: 1,
					State:    0,
					Remark:   "",
				})
			}
		}
	}
	return
}

func (o OilCard) GetDefaultOildCardNo(memberId ID) string {
	var cardNo string
	var repo data.PayRepo
	if _, _, _, mid, err := memberId.Decode(); err == nil {
		cardNo = repo.GetDefaultOildCardNo(int(mid))
	}
	return cardNo
}
